package com.wellwan.cloud.controller;

import com.wellwan.cloud.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * Copyright (C),微动天下
 * FileName: UserController
 * Author:   maokai
 * Date:     2020/2/21 10:14
 * Description:
 */
@RestController
@RequestMapping("user")
@Slf4j
public class UserController {

    @Autowired
    private RestTemplate restTemplate;
    @Value("${user.userServiceUrl}")
    private String userServiceUrl;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private LoadBalancerClient loadBalancerClient;


    @GetMapping("/{id}")
    public User findById(@PathVariable Long id) {
        User user = restTemplate.getForObject(userServiceUrl + id, User.class);
        return user;
    }

    @GetMapping("/instance")
    public List<ServiceInstance> instance() {
        return discoveryClient.getInstances("microservice-provider-user");
    }

    @GetMapping("/log-user-instance")
    public void logUserInstance() {
        ServiceInstance chooseService = this.loadBalancerClient.choose("microservice-provider-user");
            log.error("---->{}:{}:{}",chooseService.getServiceId(),chooseService.getHost(),chooseService.getPort());
        return;
    }
}
